﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Cors;
using Newtonsoft.Json.Linq;

namespace LdCms.Web.Controllers.API.Service.V1
{
    using LdCms.EF.DbModels;
    using LdCms.IBLL.Log;
    using LdCms.IBLL.Sys;
    using LdCms.IBLL.Service;
    using LdCms.Common.Net;
    using LdCms.Common.Utility;
    using LdCms.Common.Extension;
    using LdCms.Web.Services;
    using LdCms.Common.Json;
    using LdCms.Common.Enum;
    using LdCms.IBLL.Member;

    /// <summary>
    /// 服务评价接口：
    ///     功能如下 ：
    ///         1、提交评价
    ///            URL：service/comment/save?access_token=access_token
    ///            POST：{"orderid":"","images":["1.jpg","2.jpg"],"content":"","status":1,"points":5}
    ///            注：评价：status 1=不满意,2=满意 分数：points 1-5 (数字1-5)
    ///         2、追加评价
    ///            URL：service/comment/append?access_token=access_token
    ///            POST：{"commentid":"","images":["1.jpg","2.jpg"],"content":""}
    ///         3、获取评价列表-分页
    ///            GET：service/comment/list?access_token=access_token&page=1&count=10
    ///         4、获取评价明细
    ///            GET：service/comment/get?access_token=access_token&id=id
    /// 
    /// 
    /// 
    /// </summary>
    [ApiVersion("1.0")]
    [ControllerName("service/comment")]
    public class ServiceCommentController : BaseApiController
    {
        private readonly IBaseApiManager BaseApiManager;
        private readonly IHttpContextAccessor Accessor;
        private readonly ICommentService CommentService;
        private readonly ICommentAppendService CommentAppendService;
        private readonly IPointRecordService PointRecordService;
        public ServiceCommentController(IBaseApiManager BaseApiManager, IHttpContextAccessor Accessor, ICommentService CommentService, ICommentAppendService CommentAppendService, IPointRecordService PointRecordService) : base(BaseApiManager)
        {
            this.BaseApiManager = BaseApiManager;
            this.Accessor = Accessor;
            this.CommentService = CommentService;
            this.CommentAppendService = CommentAppendService;
            this.PointRecordService = PointRecordService;
        }
        /// <summary>
        /// 提交评价
        /// </summary>
        /// <param name="access_token"></param>
        /// <param name="fromValue">{"orderid":"","images":[""],"content":"","status":1,"points":5}</param>
        /// <returns></returns>
        [HttpPost]
        [ActionName("save")]
        public IActionResult SaveComment(string access_token, [FromBody]JObject formValue)
        {
            long logId = 0;
            try
            {
                logId = BaseApiManager.SaveLogs(access_token);
                bool verifyParams = IsSaveCommentParams(formValue);
                var entity = ToServiceComment(formValue);
                bool result = CommentService.SaveComment(entity);
                if (result)
                {
                    int pointClassId = (int)ParamEnum.MemberPointClass.评价;
                    int pointTypeId = (int)ParamEnum.MemberPointType.新增;
                    bool pointResult = AddPointRecordPro(pointClassId, pointTypeId, entity.OrderID, "用户评价获得积分！");
                    return Success(logId, "ok");
                }
                else
                {
                    return Error(logId, "fail");
                }
            }
            catch (Exception ex)
            {
                return Error(logId, ex.Message);
            }
        }
        /// <summary>
        /// 追加评价
        /// </summary>
        /// <param name="access_token"></param>
        /// <param name="formValue">{"commentid":"","images":["1.jpg","2.jpg"],"content":""}</param>
        /// <returns></returns>
        [HttpPost]
        [ActionName("append")]
        public IActionResult AppendComment(string access_token, [FromBody]JObject formValue)
        {
            long logId = 0;
            try
            {
                logId = BaseApiManager.SaveLogs(access_token);
                bool verifyParams = IsAppendCommentParams(formValue);
                var entity = ToServiceCommentAppend(formValue);
                bool result = CommentAppendService.SaveCommentAppend(entity);
                if (result)
                    return Success(logId, "ok");
                else
                    return Error(logId, "fail");
            }
            catch (Exception ex)
            {
                return Error(logId, ex.Message);
            }
        }
        /// <summary>
        /// 获取评价列表-分页
        /// </summary>
        /// <param name="access_token"></param>
        /// <param name="page"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        [HttpGet]
        [ActionName("list")]
        public IActionResult GetComment(string access_token)
        {
            long logId = 0;
            try
            {
                logId = BaseApiManager.SaveLogs(access_token);
                string companyId = MemberAccount.CompanyID;
                string memberId = MemberAccount.MemberID;
                int page = Utility.IsNum(GetQueryString("page"), 1);
                int count= Utility.IsNum(GetQueryString("count"), 10);
                int pageId = Utility.ToPageIndex(page);
                int pageSize = Utility.ToPageCount(count);
                int total = CommentService.CountComment(SystemID, companyId, memberId);
                var lists = CommentService.GetCommentPagingByMemberId(SystemID, companyId, memberId, pageId, pageSize);
                var data = from m in lists
                           select new
                           {
                               id = m.CommentID,
                               memberid = m.MemberID,
                               orderid = m.OrderID,
                               status = m.ServiceStatus,
                               points = m.ServicePoints,
                               image = m.Images.ToObject<string[]>(),
                               content = m.Description.IIF(),
                               date = m.CreateDate
                           };
                return Success(logId, "ok", new { page, total, rows = data });
            }
            catch (Exception ex)
            {
                return Error(logId, ex.Message);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="access_token"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        [ActionName("get")]
        public IActionResult GetCommentDetails(string access_token)
        {
            long logId = 0;
            try
            {
                logId = BaseApiManager.SaveLogs(access_token);
                int systemid = MemberAccount.SystemID;
                string companyId = MemberAccount.CompanyID;
                string commentId = GetQueryString("id");
                var entity = CommentService.GetComment(systemid, companyId, commentId);
                var lists = CommentAppendService.GetCommentAppend(systemid, companyId, commentId);
                if (entity == null)
                    return Error(logId, "not data！");
                var data = new
                {
                    id = entity.CommentID,
                    memberid = entity.MemberID,
                    orderid = entity.OrderID,
                    status = entity.ServiceStatus,
                    points = entity.ServicePoints,
                    image = entity.Images.ToObject<string[]>(),
                    content = entity.Description.IIF(),
                    details = lists.Select(m => new { image = m.Images.ToObject<string[]>(), content = m.Description }),
                    date = entity.CreateDate
                };
                return Success(logId, "ok", data);
            }
            catch (Exception ex)
            {
                return Error(logId, ex.Message);
            }
        }

        #region 私有化方法
        private Ld_Service_Comment ToServiceComment(JObject formValue)
        {
            try
            {
                string orderId = GetJObjectValue(formValue, "orderid");
                string images = GetJObjectValue(formValue, "images");
                string content = GetJObjectValue(formValue, "content");
                string status = GetJObjectValue(formValue, "status");
                string points = GetJObjectValue(formValue, "points");

                return new Ld_Service_Comment()
                {
                    SystemID = SystemID,
                    CompanyID = MemberAccount.CompanyID,
                    MemberID = MemberAccount.MemberID,
                    OrderID = orderId,
                    Images = Utility.ContentDecode(images).JsonClear(),
                    Description = content,
                    ServiceStatus = status.ToInt(),
                    ServicePoints = points.ToInt(),
                    State = true
                };
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        private Ld_Service_CommentAppend ToServiceCommentAppend(JObject formValue)
        {
            try
            {
                string commentId = GetJObjectValue(formValue, "commentid");
                string images = GetJObjectValue(formValue, "images");
                string content = GetJObjectValue(formValue, "content");

                return new Ld_Service_CommentAppend()
                {
                    SystemID = SystemID,
                    CompanyID = MemberAccount.CompanyID,
                    CommentID= commentId,
                    Images = Utility.ContentDecode(images).JsonClear(),
                    Description = content,
                    State = true
                };
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        private bool IsSaveCommentParams(JObject formValue)
        {
            try
            {
                if (formValue == null)
                    throw new Exception("params not empty！");
                if (formValue.Property("orderid") == null)
                    throw new Exception("lack orderid params！");
                if (formValue.Property("content") == null)
                    throw new Exception("lack content params！");
                if (formValue.Property("status") == null)
                    throw new Exception("lack constatustent params！");
                if (formValue.Property("points") == null)
                    throw new Exception("lack points params！");
                return true;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        private bool IsAppendCommentParams(JObject formValue)
        {
            try
            {
                if (formValue == null)
                    throw new Exception("params not empty！");
                if (formValue.Property("content") == null)
                    throw new Exception("lack content params！");
                return true;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        private bool AddPointRecordPro(int classId, int typeId, string tasksId, string body)
        {
            try
            {
                int systemId = MemberAccount.SystemID;
                string companyId = MemberAccount.CompanyID;
                string memberId = MemberAccount.MemberID;
                string className = EnumHelper.GetName<ParamEnum.MemberPointClass>(classId);
                string typeName = EnumHelper.GetName<ParamEnum.MemberPointType>(typeId);
                int points = 0;
                string account = "sys";
                string nickname = "sys";
                string ipAddress = Net.Ip;
                string remark = "";
                bool state = true;
                return PointRecordService.AddPointRecordPro(systemId, companyId, memberId, classId, className, typeId, typeName, points, tasksId, body, account, nickname, ipAddress, remark, state);
            }
            catch (Exception)
            {
                return false;
            }
        }
        #endregion

    }
}